use actix_web::{App, HttpServer};
use env_logger::{fmt::Target, Builder};
use log::{info, LevelFilter};

use actix_cors::Cors;

use sqlx::mysql::MySqlPoolOptions;

use miniprogram_management_backend::controller::index::index;

#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {
    // 初始化日志
    Builder::new()
        .filter(None, LevelFilter::Debug)
        .target(Target::Stdout)
        .init();

    // 初始化数据库连接
    let database_url = "mysql://user:password@localhost:3306/db_name";

    let pool = MySqlPoolOptions::new()
        .max_connections(5)
        .connect(&database_url)
        .await
        .expect("Failed to connect to MySQL.");

    info!("Starting server at http://localhost:8080");

    HttpServer::new(move || {
        let cors = Cors::permissive();
        App::new().wrap(cors).app_data(pool.clone()).service(index)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}
